import 'dart:math';

import 'package:chewie/chewie.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:enterprise_v6_app/app/components/empty_widget.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/emergency/barrage_list_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/emergency/emergency_event_list_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_barrage/flutter_barrage.dart';
import 'package:video_player/video_player.dart';

/// 指挥调度
class Dispatch extends StatefulWidget {
  const Dispatch({super.key});

  @override
  State<Dispatch> createState() => _DispatchState();
}

class _DispatchState extends State<Dispatch> {

  late ValueNotifier<BarrageValue> timelineNotifier;
  late VideoPlayerController videoPlayerController;
  late BarrageWallController barrageWallController;
  late ChewieController chewieController;

  /// 事故事件数据
  EmergencyEventListEntity item = Get.arguments as EmergencyEventListEntity;

  // 弹幕输入框控制器
  TextEditingController barrageController = TextEditingController();

  /// 弹幕列表
  List<BarrageListEntity> barrageList = [];

  // 发送弹幕
  void sendBarrage() async {
    if (barrageController.text.isNotEmpty) {
      final res = await HttpUtil().generatePostRequest(
        Interface.sendBarrage,
        data: {
          'barrageContent': barrageController.text,
          'createBy': '',
          'createById': '',
          'createDate': '',
          'deleted': '',
          'id': '',
          'multiMedia': item.videoPath,
          'position': timelineNotifier.value.timeline.toString(),
          'updateBy': '',
          'updateById': '',
          'updateDate': ''
        },
      ).execute();

      res.onSuccess((result) {
        // 关闭键盘
        FocusScope.of(context).requestFocus(FocusNode());
        AppToast.showSuccess('发送成功');
        barrageWallController.send([
          Bullet(child: Text(
            barrageController.text,
            style: const TextStyle(
              color: Colors.red,
            ),
          ))
        ]);
        barrageController.clear();
        // getAllBarrage(false);
      });
    }
  }

  // 根据视频路径，获取视频弹幕信息
  getAllBarrage(bool init) async {
    final res = await HttpUtil().generateGetRequest<List<BarrageListEntity>>(
      Interface.getVideoBarrage,
      queryParameters: {
        'filePath': item.videoPath,
      },
    ).execute();

    res.onSuccess((result) {
      if (result.data != null) {
        barrageList = result.data!;
        if (init) {
          initBarrage();
        }
        setState(() {});
      }
    });
  }

  // 初始化弹幕信息
  void initBarrage() {
    timelineNotifier = ValueNotifier(BarrageValue());
    videoPlayerController = VideoPlayerController.networkUrl(Uri.parse(
      item.videoPath!.startsWith('http') ? item.videoPath.toString() : '${Interface.fileUrl}${item.videoPath}',
    ))..addListener(() {
        timelineNotifier.value = timelineNotifier.value.copyWith(
          timeline: videoPlayerController.value.position.inMilliseconds,
          isPlaying: videoPlayerController.value.isPlaying,
        );
      });
    barrageWallController = BarrageWallController(timelineNotifier: timelineNotifier);

    final Random random = Random();
    final List<Bullet> bullets = List<Bullet>.generate(barrageList.length, (i) {
      final showTime = random.nextInt(1 * 30 * 1000);
      return Bullet(
        showTime: (barrageList[i].position == '' || barrageList[i].position == null) ? showTime : int.tryParse(barrageList[i].position!)!,
        child: Text(
          '${barrageList[i].barrageContent}',
          style: const TextStyle(color: Colors.white),
        ),
        // child: IgnorePointer(child: Text('$i-$showTime')),
      );
    });
    chewieController = ChewieController(
      videoPlayerController: videoPlayerController,
      aspectRatio: 16 / 9,
      autoPlay: false,
      looping: true,
      fullScreenByDefault: false,
      overlay: LayoutBuilder(builder: (context,BoxConstraints constraints) {
        debugPrint('overlay: ${constraints.maxWidth} ${constraints.maxHeight}');
        if (constraints.maxWidth > constraints.maxHeight) {
          return BarrageWall(
            width: constraints.maxWidth,
            height: constraints.maxHeight,
            // debug: true,
            // do not send bullets to the safe area
            safeBottomHeight: 60,
            // speed: 8,
            massiveMode: false,
            speedCorrectionInMilliseconds: 5000,
            controller: barrageWallController,
            timelineNotifier: timelineNotifier,
            bullets: bullets,
            child: Container(),
          );
        } else {
          return Container();
        }
      }),
    );
  }

  // 弹幕开关
  void barrageSwitch() {
    barrageWallController.isEnabled ? barrageWallController.disable() : barrageWallController.enable();
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    if (item.videoPath != null) {
      getAllBarrage(true);
    }
  }

  @override
  void dispose() {
    if (item.videoPath != null) {
      timelineNotifier.dispose();
      barrageController.dispose();
      barrageWallController.dispose();
      videoPlayerController.dispose();
      chewieController.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return item.videoPath != null
        ? Column(
            children: [
              SizedBox(
                height: 220.w,
                child: Chewie(
                  controller: chewieController,
                ),
              ),
              Container(
                height: AppDimens.dp54,
                color: const Color(0x1A5C6DFF),
                child: Row(
                  children: [
                    AppGaps.hGap16,
                    Text(
                      '弹幕',
                      style: TextStyle(
                        fontSize: 15.sp,
                      ),
                    ),
                    SizedBox(
                      height: 12,
                      child: CupertinoSwitch(
                        value: barrageWallController.isEnabled,
                        activeColor: AppColors.blue_button,
                        onChanged: (value) {
                          barrageSwitch();
                        },
                      ),
                    ),
                    AppGaps.hGap16,
                    Expanded(
                      child: Container(
                          height: 32.w,
                          padding: EdgeInsets.symmetric(horizontal: 12.w),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: Colors.white,
                              border: Border.all(color: const Color(0xffF0F0F0), width: 1.w),
                              borderRadius: BorderRadius.all(Radius.circular(8.w))),
                          child: Row(
                            children: [
                              SvgPicture.asset(
                                AppImages.icon_search,
                                width: 16.w,
                              ),
                              Expanded(
                                  child: TextField(
                                      keyboardType: TextInputType.text,
                                      textInputAction: TextInputAction.send,
                                      controller: barrageController,
                                      onSubmitted: (value) {
                                        sendBarrage();
                                      },
                                      style: TextStyle(color: const Color(0xff222222), fontWeight: FontWeight.w400, fontSize: 14.sp),
                                      decoration: InputDecoration(
                                        counterText: '',
                                        //防止适配不居中
                                        isCollapsed: true,
                                        border: const OutlineInputBorder(borderSide: BorderSide.none),
                                        contentPadding: EdgeInsets.only(left: 8.w),
                                        hintText: '请输入弹幕内容',
                                        hintStyle: TextStyle(fontSize: 14.sp, fontWeight: FontWeight.w400, color: const Color(0xffA0A7B5)),
                                        suffix: GestureDetector(
                                          onTap: sendBarrage,
                                          child: Text(
                                            '发送',
                                            style: TextStyle(fontSize: 14.sp, fontWeight: FontWeight.w400, color: Colors.blue),
                                          ),
                                        ),
                                      )))
                            ],
                          )),
                    ),
                    AppGaps.hGap16,
                  ],
                ),
              ),
              Expanded(
                child: EasyRefresh(
                  onRefresh: () async {
                    getAllBarrage(false);
                  },
                  child: ListView.separated(
                    padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 10.w),
                    itemCount: barrageList.length,
                    itemBuilder: (context, index) {
                      return Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(barrageList[index].createBy ?? '',
                                  style: TextStyle(
                                    fontSize: 14.sp,
                                    color: const Color(0xffA0A7B5),
                                  )),
                              Text(barrageList[index].createDate ?? '',
                                  style: TextStyle(
                                    fontSize: 12.sp,
                                    color: const Color(0xffA0A7B5),
                                  ))
                            ],
                          ),
                          SizedBox(
                            height: 5.w,
                          ),
                          Align(
                            alignment: Alignment.centerLeft,
                            child: Text(barrageList[index].barrageContent ?? '',
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: const Color(0xff222222),
                                )),
                          )
                        ],
                      );
                    },
                    separatorBuilder: (context, index) {
                      return Container(
                        height: 1.w,
                        margin: const EdgeInsets.only(
                          top: 16,
                          bottom: 16,
                        ),
                        color: Colors.grey.withOpacity(0.2),
                      );
                    },
                  ),
                ),
              )
            ],
          )
        : EmptyWidget.getEmptyWidget();
  }
}
